// pages/orderMgt/orderInfo/orderInfo.js
const app = getApp();
import Common from '../../../../common/common.js';
let common = new Common;
Page({
  data: {
    fhAble: true,//配送按钮屏蔽
    quDisable: false, //取货码按钮
    wuliuData: '',
    codeVal: '', //取货码
    quhuoShow: false, //取货码弹窗
    userType: '',
    isHaveUserNum: 0, //店员数量
    psuser: '', //选择的配送员信息
    psType: 0, //配送方式1自提 2业务员配送  3物流配送
    windowsType: 0, //弹出层类型，1配送方式 2配送员信息 3物流信息
    psUserInfo: '', //配送员信息
    infoData: {}, //订单详情
    orderItemTemplate: '',//定制的信息
    loadingShow: true,
    ordertype: '',//判断列表入口  0 订单 1配送订单
  },
  //查看
  previewImage(e) {
    let imageurl = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [imageurl],
      current: imageurl,
      success: res => {
        console.log('预览')
      }
    })
  },
  onLoad: function (options) {
    console.log(options)
    if (options.id) {
      this.setData({
        id: options.id || '',
        userType: app.globalData.shopInfo.userType || '',
        orgSeq: app.globalData.orgSeq || '',
        psType: options.psType || 0, //配送方式
      })
    } else {
      wx.showToast({
        title: '参数错误，马上返回',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1200)
    }
    this.getOrderDetails();
    //查询看看有没有店员
    this.getUserList();
  },
  onShow: function () {
    //查询配人信息
    this.getPsUserInfo();

    //拿到选择配送员的返回参数
    if (wx.getStorageSync('psuser')) {
      this.setData({
        psuser: wx.getStorageSync('psuser'),
        windowsType: 2
      })
      wx.setStorageSync('psuser', '')
    }

    //拿到选择物流信息返回
    if (wx.getStorageSync('wuliuData')) {
      this.setData({
        wuliuData: wx.getStorageSync('wuliuData'),
        windowsType: 3
      })
      wx.setStorageSync('wuliuData', '')
    }
  },
  // 查询配送员信息
  getPsUserInfo() {
    let data = {
      orderId: this.data.id,
    }
    common.requestAjax('/api/trade-service/v1/myorder/getDeliveryInfoByOrderId', 'GET', data).then(res => {
      if (res.data.code) {
        this.setData({
          psUserInfo: res.data.result
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },
  //获取订单详情
  getOrderDetails() {
    // wx.showToast({
    //   title: '加载中',
    //   icon: 'loading'
    // });
    let data = {
      orderId: this.data.id,
    }
    common.requestAjax('/api/trade-service/v1/trade/queryOrderById', 'GET', data).then(res => {
      if (res.data.code == 1) {
        this.setData({
          infoData: res.data.result,
          orderItemTemplate: res.data.result.items[0].orderItemTemplate || '',
          loadingShow: false,
        })
        console.log(this.data.infoData)
        // setTimeout(() => {
        //   wx.hideToast();
        // }, 1200)
        if (this.data.userType == 6) {
          this.setData({
            psId: res.data.result.userId,
          })
        }
        if (res.data.result.payStatus == 3) {
          //支付状态未刷新
          this.refreshPayStatus();
        }
      }
    }).catch(err => {
      console.log(err);
    })
  },
  //支付状态刷新
  refreshPayStatus() {
    let data = {
      orderId: this.data.id
    }
    common.requestAjax('/api/pay-service/v1/pay/onlinePayQuery', 'POST', data).then(res => {
      if (res.data.code) {
        //重新刷新状态
        this.getOrderDetails()
      }
    })
  },
  //线下支付方式 要门店手动确认付款
  paySure: function (e) {
    let that = this;
    let data = {
      orderId: that.data.id,
    }
    wx.showModal({
      title: '确认客户已支付？',
      content: '请确认客户已经线下付款，确认后不可取消哦!',
      success: function (res) {
        console.log(res)
        if (res.cancel) {
          console.log('点击取消')
        } else {
          common.requestAjax('/api/trade-service/v1/trade/orderPay', 'GET', data).then(res => {
            if (res.data.code == 1) {
              that.getOrderDetails();
              wx.showToast({
                title: '收款成功！',
                icon: 'none'
              })
            }
          }).catch(err => {
            console.log(err);
          })
        }
      }
    })
  },
  // 点击配送选择配送方式
  codeps: function (e) {
    if (this.data.userType == 6) {
      this.setData({
        windowsType: 2,
        psuser: {
          userId: this.data.infoData.userId,
          realName: this.data.infoData.userName,
          tel: this.data.infoData.userTel,
          headPicUrl: this.data.infoData.headPicUrl
        }
      })
    } else {
      this.setData({
        windowsType: 1
      })
    }

  },
  hideShow() {
    this.setData({
      windowsType: 0
    })
  },
  //  选择配送方式
  changPsType: function (e) {
    let psType = e.currentTarget.dataset.pstype;
    this.setData({
      psType,
    });
    if (psType == 2) {
      //配送
      //如果没有店员或者操作者为店员，默认自己配送
      if (this.data.isHaveUserNum == 0 || this.data.userType == 6) {
        this.setData({
          windowsType: 2,
          psuser: {
            userId: this.data.infoData.userId,
            realName: this.data.infoData.userName,
            tel: this.data.infoData.userTel,
            headPicUrl: this.data.infoData.headPicUrl
          }
        })
      } else {
        wx.navigateTo({
          url: '/pages/orderMgt/chooseEmploySend/chooseEmploySend?&orderId=' + this.data.id,
        })
      }
    } else {
      //物流
      wx.navigateTo({
        url: '/pages/orderMgt/changWuliuCompany/changWuliuCompany?orderId=' + this.data.id
      })
    }
  },
  //查询看有没有店员
  getUserList: function () {

    common.requestAjax('/api/user-service/v1/user/queryUsersById', 'POST', {
      page: 1,
      size: 99,
      condition: {
        orgSeq: this.data.orgSeq
      }
    }).then(res => {
      if (res.data.code == 1) {
        this.setData({
          isHaveUserNum: res.data.records.length,
        })
      }
    }).catch(err => {
      console.log(err);
    })
  },

  // 提交配送生成配送单
  setDistribution: function (e) {
    let data = {
      orgSeq: this.data.orgSeq, //店铺id
      orderId: this.data.id, //订单id
      deliveryType: this.data.psType, //配送方式（1自提、2业务员、3快递公司）
      userId: this.data.psuser.userId || '', //业务员id
      companyId: this.data.wuliuData.wuliuid || '', //快递公司id
      deliveryNo: this.data.wuliuData.wuliuno || '', //快递单号
      companyName: this.data.wuliuData.wuliuname || '' //快递名称
    }
    this.setData({
      fhAble: false
    })
    
    common.requestAjax('/api/trade-service/v1/myorder/saveDeliveryInfo', 'POST', data).then(res => {
      if (res.data.code) {
        this.getOrderDetails();
        this.hideShow();
        wx.showToast({
          title: '提交配送信息成功，发货成功！',
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: res.data.message,
          icon: 'none'
        })
        setTimeout(() => {
          this.setData({
            fhAble: true
          })
        }, 1000)
      }
    }).catch(err => {
      console.log(err)
    })

    log.info(`api:saveDeliveryInfo;${JSON.stringify(data)};订单:${this.data.id}`);
  },
  //弹开取货码
  showQhuoCode() {
    this.setData({
      quhuoShow: true
    })
  },
  // 扫码
  scanCode: function (e) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        let result = res.result;
        result = result.substring(result.length - 6)
        that.setData({
          codeVal: result,
        })
      }
    })
  },
  hideQuhuo() {
    this.setData({
      quhuoShow: false
    })
  },

  getVal(e) {
    this.setData({
      codeVal: e.detail.value
    })
  },

  setTihuoCode: function (e) {
    if (this.data.infoData.tdcode == this.data.codeVal) {
      this.setData({
        quDisable: true
      })
      this.orderSend(() => {
        let data = {
          orderId: this.data.id
        }
        common.requestAjax('/api/trade-service/v1/trade/orderCompleted', 'GET', data).then(res => {
          if (res.data.code) {
            //更新状态
            this.getOrderDetails();
            this.hideQuhuo();
            wx.showToast({
              title: '验证完成，收货成功！',
              icon: "none"
            })
          } else {
            wx.showToast({
              title: '验证失败！' + res.data.message,
              icon: "none"
            })
          }

          this.setData({
            codeVal: '',
            quDisable: false
          })

        }).catch(err => {
          wx.showToast({
            title: '取货码错误！',
            icon: 'none',
          })
        })
      })
    } else {
      wx.showToast({
        title: '取货码不正确,请重新输入！',
        icon: 'none',
      })
    }
  },

  sureDelivery: function () {
    wx.showModal({
      title: "提示",
      content: '该订单为线下自提订单,是否发货？',
      success: res => {
        if (res.confirm) {
          let userId = 'psuser.userId'
          this.setData({
            psType: 1, //4、配送方式（1门店自提2业务员、3快递公司）
            [userId]: this.data.infoData.userId
          })
          this.setDistribution();
        }
      }
    })
  },
  //查看宴会信息
  toLookyanhui() {
    let tradeFeastInfo = this.data.infoData.tradeFeastInfo;
    wx.navigateTo({
      url: `../yanhuiPage/index?tradeFeastInfo=${JSON.stringify(tradeFeastInfo)}&islook=1`,
    })
  },
  //自动发货
  orderSend(succ) {
    let data = {
      orderId: this.data.id,
      deliveryMethod: 1
    }
    common.requestAjax('/api/trade-service/v1/trade/orderSend', 'GET', data).then(res => {
      if (res.data.code) {
        succ && succ()
      } else {
        wx.showToast({
          title: res.data.message,
          icon: "none"
        })
      }
    })
  }
})